package com.wdh.networklibrary.net;

import android.text.TextUtils;

import com.erongdu.wireless.tools.log.Logger;
import com.wdh.networklibrary.mvp.view.BaseView;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.subscribers.ResourceSubscriber;
import retrofit2.HttpException;

/**
 * 统一订阅管理
 *
 * @param <T> 泛型
 */
public abstract class ApiSubscriber<T> extends ResourceSubscriber<T> {
    private BaseView view;

    protected ApiSubscriber(BaseView view) {
        this.view = view;
    }

    protected ApiSubscriber() {
    }



    @Override
    public void onError(Throwable t) {
        if (null != view) {
            Logger.i("toast", "onError:"+t.getMessage());
            String msg;
            if (t instanceof HttpException) {
                /*网络异常*/
                msg = "网络异常，请确保网络可用!";
            } else if (t instanceof ConnectException || t instanceof SocketTimeoutException) {
                msg = "请求超时，请稍后重试!";
            } else if (t instanceof JSONException || t instanceof ParseException) {
                /*解析异常*/
                msg = "数据解析异常，请稍后重试!";
            } else if (t instanceof UnknownHostException) {
                /*无法解析该域名异常*/
                msg = "无法解析该域名，请稍后重试!";
            } else {
                msg = "请求失败，请稍后重试!";
            }
            if (TextUtils.isEmpty(msg)) {
                view.onFailure(t.getMessage());
            }else {
                view.onFailure(msg);
            }
        }
    }

    @Override
    public void onComplete() {
        if (null != view) {
            view.onComplete();
        }
    }
}
